// ==UserScript==
// @name         职教云icve※智慧职教 答案提取/填充
// @description  职教云icve※智慧职教 答案提取/填充
// @author       皇家养猪场
// @namespace    皇家养猪场
// @version      1.2.7
// @create       2021-04-20
// @lastmodified 2021-05-17
// @note         目前功能已稳定，近期不会再大更新。如有什么功能需求/好点子/bug，请反馈QQ1523789353
// @charset      UTF-8
// @updateURL    http://81.71.31.250/QuizTool.js
// @downloadURL  http://81.71.31.250/QuizTool.js
// @require      https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.5.1.min.js
// @match        *://*.icve.com.cn/*
// @connect      81.71.31.250
// @connect      localhost
// @run-at       document-idle
// @grant        unsafeWindow
// @grant        GM_xmlhttpRequest
// @grant        GM_getValue
// @grant        GM_setValue
// @compatible   chrome
// @license      MIT
// ==/UserScript==

var Root = this;

function QuizTool(config) {
	var Self = this;
	this.config = config;

	if (Self.config.SafeMode == "true") {
		var notice = (str,a,b,c,d) => {
			console.log(str);
		}
	} else {
		$('<div id="msgbox"></div>').css({
			"position": "fixed",
			"width": "100%",
			"text-align": "center",
			"z-index": "9999",
			"pointer-events": "none"
		}).prependTo('body')
		var notice = (str,In,Keep,Out,bg) => {
			setTimeout(
				(e,o)=>{e.fadeTo(o,0).slideUp(o,function(){$(this).remove()})},
				Keep,
				$('<span></span><br>').text(str).css({
					"display": "inline-block",
					"margin": "4px 0",
					"padding": ".5em 1em",
					"background": (bg?bg:"#FFF"),
					"backdrop-filter": "blur(1px)",
					"box-shadow": "2px 2px 4px rgba(0,0,0,.35)",
					"border": "solid 1px rgba(0,0,0,.15)",
					"border-radius": "8px",
					"text-align": "center",
					"opacity": "0",
					"user-select": "none",
					"pointer-events": "none"
				}).appendTo('#msgbox').fadeTo(In,1),
				Out
			)
		}
	}
	notice("QuizTool运行中...", 500, 3000, 500, "rgba(0,0,0,0)");

	this.initData = () => {
		Self.JsonObj = new Object();
		Self.trimData();
	}
	this.exportData = () => {
		console.log(GM_getValue('QuizToolJsonData'));
	}
	this.importData = (Json) => {
		$(Self.JsonObj).attr(Json);
		Self.trimData();
	}
    this.trimData = () => {
		var tmp = new Object();
		for (var ID in Self.JsonObj) {
			if (Self.JsonObj[ID] != undefined && Self.JsonObj[ID].length != 0 && Self.JsonObj[ID].length <= 4) $(tmp).attr(ID,Self.JsonObj[ID]);
		}
		Self.JsonObj = tmp;
		GM_setValue('QuizToolJsonData', JSON.stringify(Self.JsonObj));
	}
	this.base64 = (str) => {
		return btoa(unescape(encodeURIComponent(str)));
	}
	this.debase64 = (str) => {
		return decodeURIComponent(escape(atob(str)));
	}
	try {
		this.JsonObj = JSON.parse(GM_getValue('QuizToolJsonData'));
	} catch (e) {
		notice("读取数据失败:"+e+",初始化数据...", 500, 3000, 500, "rgba(0,0,0,0)");
		Self.initData()
	}
	
	this.cloudSync = () => {
		GM_xmlhttpRequest({
			method: "GET",
			url: 'http://81.71.31.250/QuizData.json',
			onload: function(res) {
				if (res.status == 200) {
					try {
						Self.importData(JSON.parse(res.responseText));
						notice("云同步成功.", 500, 3000, 500, "rgba(0,0,0,0)");
					} catch (e) {
						notice("云同步失败:导入数据出错! "+e, 500, 3000, 500, "rgba(0,0,0,0)");
					}
				} else notice("云同步失败:网络错误("+res.status+")", 500, 3000, 500, "rgba(0,0,0,0)");
			}
		});
	}
	this.get = () => {
		var Framework = $('div.np-wrapper>div.np-container>div.np-contenter>div.hasNoLeft>form#indexForm>div#container>div#homework_div');
		if (Framework.length == 0) Framework = $('div.np-wrapper>div.np-container>div.np-contenter>div.hasNoLeft>div#dataForm>div#container>div.center-all');
		if (Framework.find('div.e-q-panel.e-q-panel-paper.typebox.bigquestionblock').length != 0) return;	//非答案页
		var last = Framework.find('div.e-q-body').length;
		if (last == 0) return;	//无题目。。？
		var obj = new Object();
		for (var ID = 1; ID <= last; ID++) {
			var target = Framework.find('div.e-q-body[data-num='+ID+']');
			obj[target.attr("data-questionid")] = $(target.find('div.e-ans-ref.am-cf')[0]).find('span.e-ans-r').text();
		}
        Self.importData(obj);
		notice("已提取"+last+"个答案.", 500, 3000, 500, "rgba(0,0,0,0)");
	}
	this.search = () => {
		var Framework = $('body>div.np-wrapper>div.np-container>div.np-contenter>div.hasNoLeft>div#dataForm>div#container>div>div.am-cf.wl_types>div.center-all>div.e-q-panel.e-q-panel-paper.typebox.bigquestionblock');	//作业
		if (Framework.length == 0) Framework = $('body>div.np-wrapper>div.np-container>div.np-contenter>div.hasNoLeft>div#dataForm>div#container>div.center-all>div.e-q-panel.e-q-panel-paper.typebox.bigquestionblock');	//考试
		var last = Framework.find('div.e-q-body.questionSortOrder').length;
		if (last == 0) return;
		var notFound = new Array();
		var unknowType = new Array();
		var Handle = (Target) => {(Self.config.SafeMode == "true") ? Target.children('div.ErichText.destroyTitleButton').css("background-color", "#F0FFF0") : Target.click(); }
		for(var n = 1; n <= last; n++){
			var Quest = Framework.find('div.e-q-body.questionSortOrder[data-num='+n+']');
			try {
				var Answer = $(Self.JsonObj).attr(Quest.attr("data-questionid")).toString();
			} catch (e) {
				notFound.push(n);
				continue;
			}
			switch (Quest.attr("data-questiontype")) {
				case "1":
					Handle(Quest.children("form").find('ul>li.e-a[data-index='+["A", "B", "C", "D"].indexOf(Answer)+']'));
					break;
				case "2":
					(Self.config.SafeMode == "true") ? Quest.children("form").find('ul>li.e-a.checked').children('div.ErichText.destroyTitleButton').css("background-color", "#FFF0F0") : Quest.children("form").find('ul>li.e-a.checked').click();
					for(var i = 0; i < Answer.length; i++) {
						Handle(Quest.children("form").find('ul>li.e-a[data-index='+["A", "B", "C", "D"].indexOf(Answer[i])+']'));
					}
					break;
				case "3":
					Handle(Quest.children("form").find('ul>li.e-a[data-index='+(Answer == "A" ? 1 : 0)+']'));
					break;
				default:
					unknowType.push(n);
					break;
			}
		}
		$('input[name="UseTime"]').attr("value",Math.round(Math.random()*600+last*10));
		notice("答题完毕.", 500, 3000, 500, "rgba(0,0,0,0)");
		if (notFound.length != 0) notice("未找到第"+notFound.toString()+"题答案!",500,5000,500,"rgba(0,0,0,0)");
		if (unknowType.length != 0) notice("未找到第"+unknowType.toString()+"题的题型!", 500, 5000, 500, "rgba(0,0,0,0)");
		if (notFound.length + unknowType.length != 0) notice("您可以尝试清除浏览器缓存!", 500, 5000, 500, "rgba(0,0,0,0)");
	}
	this.help = () => {console.log('欢迎使用QuizTool,以下是支持的函数:\n  document.QT.cloudSync\t\t 云同步答案\n  document.QT.get\t\t\t*尝试提取答案页的答案\n  document.QT.search\t\t*尝试填写题目\n  document.QT.exportData\t 导出数据\n  document.QT.importData\t 导入数据(现有条目会被覆盖)\n  document.QT.trimData\t \t 整理并存储数据\n  document.QT.initData\t\t 初始化数据\n\n如果有答不了的题肯定不是我的问题，肯定不是！(> <)'); }
}

setTimeout(() => {
    document.onfocusout = window.onblur = undefined;
    if (typeof Root.config == "undefined") Root.config = {};
	document.QT = new QuizTool(Root.config);
	document.QT.search();
	document.QT.cloudSync();
	setTimeout(() => {
		document.QT.get();
        if ($('video').length > 0) {
            for (var i = 0; i < $('video').length; i++) {
                $('video')[i].playbackRate = 16;
            }
        }
    }, 500);
}, 1500);

//安全模式:无Toast消息弹窗/不自动答题/正确答案显示弱绿色背景
//this.config = {SafeMode: "true"}
